// pages/collect/collect.js
let app = getApp()
// 获取云数据库引用
const db = wx.cloud.database()
const admin = db.collection('adminlist')
const thisMsg = wx.getStorageSync('loginMsg') && JSON.parse(wx.getStorageSync('loginMsg'))

Page({

  /**
   * 页面的初始数据
   */
  data: {
    collect_ph: [],
    collect_st: [],
    ph_onLoading: false,
    st_onLoading: false
  },

  // 获取当前用户的收藏数组
  onGetCollect () {
    let that = this
    let _id = thisMsg._id
    let collectPh, collectSt
    if (_id !== undefined) {
      admin.doc(_id).get({
        success (res) {
          // res.data 包含该记录的数据
          collectPh = res.data.collect_ph
          collectSt = res.data.collect_st
          that.setData({
            collect_ph: collectPh,
            collect_st: collectSt
          })
        }
      })
    }
  },

  // 取消收藏平花
  cancelPH (e) {
    let that = this
    let thisIndex = e.currentTarget.dataset.index
    let _id = thisMsg._id
    if (_id !== undefined) {
      admin.doc(_id).get({
        success (res) {
          // res.data 包含该记录的数据
          that.setData({
            collect_ph: collectPh
          })
        }
      })
    }
    const collectPh = this.data.collect_ph
    collectPh.splice(thisIndex, 1)
    if (_id !== undefined) {
      admin.doc(_id).update({
        data: {
          collect_ph: collectPh
        }
      })
        .then((res) => {
          wx.showToast({
            title: '取消收藏成功',
            icon: 'success',
            mask: true,
            duration: 1000
          })
        })
    }
    this.onGetCollect()
  },
  // 取消收藏刹车
  cancelST (e) {
    let that = this
    let thisIndex = e.currentTarget.dataset.index
    let _id = thisMsg._id
    if (_id !== undefined) {
      admin.doc(_id).get({
        success (res) {
          // res.data 包含该记录的数据
          that.setData({
            collect_st: collectSt
          })
        }
      })
    }
    let collectSt = this.data.collect_st
    collectSt.splice(thisIndex, 1)
    if (_id !== undefined) {
      admin.doc(_id).update({
        data: {
          collect_st: collectSt
        }
      })
        .then((res) => {
          wx.showToast({
            title: '取消收藏成功',
            icon: 'success',
            mask: true,
            duration: 1000
          })
        })
    }
    this.onGetCollect()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    this.onGetCollect()
  },

  // 点击播放视频
  videoPlay (e) {
    let _index = e.currentTarget.dataset.id
    this.setData({
      _index: _index
    })
    // 停止正在播放的视频
    let videoContextPrev = wx.createVideoContext(_index + '')
    videoContextPrev.stop()

    setTimeout(function () {
      // 将点击视频进行播放
      let videoContext = wx.createVideoContext(_index + '')
      videoContext.play()
    }, 200)
  },

  // 视频播放出错
  videoErrorCallback (e) {
    console.log('视频错误信息:')
    console.log(e.detail.errMsg)
  }
})
